package com.shipwe.loans.ui.adapter

import android.annotation.SuppressLint
import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.shipwe.adapter.ShipweRecyclerViewAdapter
import com.shipwe.adapter.ShipweViewHolderHelper
import com.shipwe.loans.MyApps
import com.shipwe.loans.R
import com.shipwe.loans.utils.ShipweDateUtil
import com.shipwe.loans.utils.AppLoadImageUtil
import com.shipwe.loans.utils.helper.CustomConfigsHelper
import com.shipwe.loans.utils.helper.UserPointsHelper
import org.json.JSONObject
import java.math.BigDecimal

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/13 10:55
 * @Annotation：待还款列表
 */
class OrderRepayAdapter(recyclerView: RecyclerView?): ShipweRecyclerViewAdapter<JSONObject>(recyclerView) {

    private val TYPE_POINTS_TIPS = "TYPE_POINTS_TIPS"//剩余积分使用提示
    private val TYPE_ORDER = "TYPE_ORDER"//订单
    private val TYPE_EMPTY = "TYPE_EMPTY"//空提示

    override fun getItemViewType(position: Int): Int {
        val model = getItem(position)
        return when (model.optString("itemType")) {
            TYPE_POINTS_TIPS -> {//剩余积分使用提示
                R.layout.repay_item_have_points
            }
            TYPE_EMPTY -> {//空提示
                R.layout.repay_item_empty
            }
            else -> {//订单
                R.layout.fragment_order_repay_item
            }
        }
    }

    override fun setItemChildListener(helper: ShipweViewHolderHelper, viewType: Int) {
        helper.setItemChildClickListener(R.id.repayEmptyText)//去申请
        helper.setItemChildClickListener(R.id.orderRepayDetails)//还款详情
    }

    override fun fillData(helper: ShipweViewHolderHelper, position: Int, model: JSONObject) {
        when (model.optString("itemType")) {
            TYPE_POINTS_TIPS -> {
                showOrderRepayHavePointsView(helper, position, model)
            }
            TYPE_EMPTY -> {//空提示
                showOrderRepayEmptyView(helper, position, model)
            }
            else -> {
                showOrderRepayOrderView(helper, position, model)
            }
        }
    }

    /**
     * 可使用积分提示
     */
    private fun showOrderRepayHavePointsView(helper: ShipweViewHolderHelper, position: Int, model: JSONObject) {
        val repayPointTips = helper.getTextView(R.id.repayPointTips)
        val pointText = String.format(MyApps.app.getString(R.string.repay_have_points_key),model.optString("points"))
        val showText = String.format(MyApps.app.getString(R.string.repay_have_points_tips),pointText)
        val spString = SpannableString(showText)
        val start = showText.indexOf(pointText)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FFFF5000")), start, start+pointText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        repayPointTips.text = spString
    }

    /**
     * 没有待还款订单提示
     */
    private fun showOrderRepayEmptyView(helper: ShipweViewHolderHelper, position: Int, model: JSONObject) {
        val textRepayEmpty = helper.getTextView(R.id.repayEmptyText)
        val applyTips = MyApps.app.getString(R.string.product_empty_apply)
        val showText = String.format(MyApps.app.getString(R.string.repay_empty_tips),applyTips)
        val spString = SpannableString(showText)
        val start = showText.indexOf(applyTips)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#000000")), start, start+applyTips.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //添加下划线
        spString.setSpan(UnderlineSpan(), start, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        textRepayEmpty.text = spString
    }

    /**
     * 待还款订单
     */
    @SuppressLint("SetTextI18n")
    private fun showOrderRepayOrderView(helper: ShipweViewHolderHelper, position: Int, model: JSONObject) {
        //可获得积分数
        helper.setText(R.id.repayAddPoints,String.format(MyApps.app.getString(R.string.points_add_count),model.optString("score")))
        val imgLogo = helper.getImageView(R.id.orderRepayLogo)
        AppLoadImageUtil.instance.loadImageUrl(mContext, imgLogo, model.optString("logo"), R.drawable.load_holder)
        helper.setText(R.id.orderRepayTitle, model.optString("name"))

        val textRepaymentAmount = helper.getTextView(R.id.orderRepayAmount)
        val showAmount = BigDecimal(model.optString("repayAmount")).stripTrailingZeros().toPlainString()
        textRepaymentAmount.text = "$showAmount ${model.optString("currency")}"

        val repaymentDate = model.optString("repaymentDate")
        val repaymentTimestamp = ShipweDateUtil.convertDateToTimestamp(repaymentDate)
        helper.setText(R.id.orderRepayDueDate, ShipweDateUtil.getFormatTime(repaymentTimestamp,"dd/MM/yyyy"))

        val textStatus = helper.getTextView(R.id.orderRepayStatus)
        //逾期时间
        val overdueDay = model.optString("overdueDay").toInt()
        if (overdueDay > 0) {//逾期时长
            textStatus.setTextColor(Color.parseColor("#FFEC273A"))
            textStatus.text = String.format(MyApps.app.getString(R.string.repay_days_overdue),"$overdueDay")
        } else {
            textStatus.setTextColor(Color.parseColor("#FF222222"))
            textStatus.text = String.format(MyApps.app.getString(R.string.repay_days_left), model.optString("remainRepayDay"))
        }

        //当前积分数
        val curtPoints = BigDecimal("${UserPointsHelper.getShipweUserPoints()}")
        //所有积分可抵扣金额  乘 multiply
        val maxDiscountAmount = curtPoints.multiply(BigDecimal(CustomConfigsHelper.getShipweChangeRate()))
        //当前订单可使用积分抵扣的最大金额 = 借款金额 * 最大抵扣比例
        val curtMaxDiscountAmount = BigDecimal(model.optString("amount","0")).multiply(BigDecimal(CustomConfigsHelper.getShipweDiscountRate()))
        //可以抵消积分
        var discountPoints = BigDecimal(maxDiscountAmount.toInt()).divide(BigDecimal(CustomConfigsHelper.getShipweChangeRate())).toPlainString()
        //积分可抵扣的最大金额 > 当前订单可用积分抵扣的最大金额 -> 当前订单可抵扣的最大金额
        if (maxDiscountAmount > curtMaxDiscountAmount){
            discountPoints = curtMaxDiscountAmount.divide(BigDecimal(CustomConfigsHelper.getShipweChangeRate())).stripTrailingZeros().toPlainString()
        }

        val showPoints = String.format(MyApps.app.getString(R.string.repay_have_points_key),discountPoints)
        val showText = String.format(MyApps.app.getString(R.string.repay_points_can_be_offset),showPoints)
        val showIndex = showText.indexOf(showPoints)
        val spString = SpannableString(showText)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FFFF5000")), showIndex, showIndex + showPoints.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        helper.setText(R.id.orderRepayPointsOffset,spString)

        if (discountPoints.toInt() == 0){
            helper.setVisibility(R.id.orderRepayPointsOffset, View.INVISIBLE)
        } else {
            helper.setVisibility(R.id.orderRepayPointsOffset, View.VISIBLE)
        }
    }
}